package com.junjie.checkin.websocket.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.user.SimpUser;
import org.springframework.messaging.simp.user.SimpUserRegistry;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class WebSocketSessionService {

    @Autowired
    private SimpUserRegistry simpUserRegistry;

    /**
     * 获取所有活跃会话的详细信息
     * @return Map<用户名, Map<Session ID, 订阅路径列表>>
     */
    public Map<String, Map<String, List<String>>> getActiveSessions() {
        return simpUserRegistry.getUsers().stream()
                .collect(Collectors.toMap(
                        SimpUser::getName,
                        user -> user.getSessions().stream()
                                .collect(Collectors.toMap(
                                                session -> session.getId(),
                                                session -> session.getSubscriptions().stream()
                                                        .map(sub -> sub.getDestination())
                                                        .collect(Collectors.toList())
                                        )
                                )));
    }

    /**
     * 获取所有订阅了特定路径的用户
     * @param destination 订阅路径（如 "/topic/activity"）
     * @return 用户名列表
     */
    public List<String> getUsersSubscribedTo(String destination) {
        return simpUserRegistry.getUsers().stream()
                .filter(user -> user.getSessions().stream()
                        .anyMatch(session -> session.getSubscriptions().stream()
                                .anyMatch(sub -> sub.getDestination().equals(destination))
                        )
                )
                .map(SimpUser::getName)
                .collect(Collectors.toList());
    }
}